package com.otp.service.impl;

import com.otp.pojo.entity.Resource;
import com.otp.exception.BusinessException;
import com.otp.repository.ResourceRepository;
import com.otp.pojo.request.resource.ResourceCreateRequest;
import com.otp.pojo.request.resource.ResourceUpdateRequest;
import com.otp.service.FileService;
import com.otp.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceRepository resourceRepository;

    @Autowired
    private FileService fileService;

    @Override
    public List<Resource> list() {
        return resourceRepository.findAll();
    }

    @Override
    public List<Resource> listByCategory(String category) {
        return resourceRepository.findByCategory(category);
    }

    @Override
    public Resource getById(Long id) {
        return resourceRepository.findById(id)
                .orElseThrow(() -> new BusinessException("资源不存在"));
    }

    @Override
    public Resource create(ResourceCreateRequest request) {
        validateRequest(request.getFile(), request.getCategory());
        try {
            String fileUri = fileService.upload(request.getFile());
            Resource resource = new Resource();
            resource.setTitle(request.getTitle());
            resource.setCategory(request.getCategory());
            resource.setFileType(getFileExtension(request.getFile()));
            resource.setFileSize(request.getFile().getSize());
            resource.setFileUri(fileUri);
            resource.setUploadTime(LocalDateTime.now());
            return resourceRepository.save(resource);
        } catch (IOException e) {
            throw new BusinessException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public Resource update(ResourceUpdateRequest request) {
        Resource resource = getById(request.getId());
        resource.setTitle(request.getTitle());
        resource.setCategory(request.getCategory());
        if (request.getFile() != null && !request.getFile().isEmpty()) {
            validateRequest(request.getFile(), request.getCategory());
            try {
                // 删除旧文件
                fileService.delete(resource.getFileUri());
                String fileUrl = fileService.upload(request.getFile());
                resource.setFileUri(fileUrl);
                resource.setFileType(getFileExtension(request.getFile()));
                resource.setFileSize(request.getFile().getSize());
            } catch (IOException e) {
                throw new BusinessException("文件更新失败: " + e.getMessage());
            }
        }
        return resourceRepository.save(resource);
    }

    @Override
    public void delete(Long id) {
        Resource resource = getById(id);
        fileService.delete(resource.getFileUri());
        resourceRepository.deleteById(id);
    }

    private void validateRequest(MultipartFile file, String category) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException("文件不能为空");
        }
        if (file.getSize() > 100 * 1024 * 1024) { // 限制100MB
            throw new BusinessException("文件大小不能超过100MB");
        }
        if (!List.of("DOCUMENT", "VIDEO", "AUDIO", "IMAGE").contains(category)) {
            throw new BusinessException("无效的资源分类");
        }
    }

    private String getFileExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase() : "";
    }
}